package com.rain.shoppingscienceproj.ui.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.Goods;
import com.rain.shoppingscienceproj.module.ShoppingcarDto;
import com.rain.shoppingscienceproj.module.UserInfo;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.utils.ImageUtils;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;

/**
 * Author: Rain
 * Create: 2018/9/3 0:07
 */
public class CarGoodsAdapter extends RecyclerView.Adapter<CarGoodsAdapter.MyViewHolder> {

    private Context mContext;
    private List<ShoppingcarDto> list;
    private CheckItemClickListener checkItemClickListener;
    private LongItemListener longItemListener;
    private CountListenter countListenter;
    private int num = 0;
    private UserInfo userInfo = GlobalData.getUserInfo();


    public CarGoodsAdapter(Context mContext) {
        this.mContext = mContext;
    }

    public void setCheckItemClickListener(CheckItemClickListener checkItemClickListener) {
        this.checkItemClickListener = checkItemClickListener;
    }

    public void setLongItemListener(LongItemListener longItemListener) {
        this.longItemListener = longItemListener;
    }

    public void setCountListenter(CountListenter countListenter) {
        this.countListenter = countListenter;
    }

    public void setList(List<ShoppingcarDto> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public void selectAllGoods(boolean allSelect) {
        if (allSelect) {
            num = list.size();
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSelect(true);
            }
        } else {
            num = 0;
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setSelect(false);
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.car_goods_layout, parent, false);//解决宽度不能铺满
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        ShoppingcarDto goods = list.get(position);
        if (null != goods.getGoodsImage() || !"".equals(goods.getGoodsImage())) {
            ImageUtils.imageRound(mContext, goods.getGoodsImage(), holder.iv_image);
        }
        holder.tv_title.setText(goods.getGoodsName());
        holder.tv_money.setText(goods.getGoodsPay() / 100 + "");
        holder.tv_num.setText(goods.getSize()+"");

        if (goods.isSelect)
            holder.iv_check.setImageResource(R.drawable.address_complete);
        else
            holder.iv_check.setImageResource(R.drawable.wallet_recharge_checkbox);


        holder.ll_item.setOnLongClickListener(v -> {
            longItemListener.LongItemLister(goods, position);
            return false;
        });

        holder.ll_check.setOnClickListener(view -> {
            check(goods, holder.iv_check);
        });

        holder.iv_add.setOnClickListener(view -> {
            int num = goods.getSize();
            num++;
            goods.setSize(num);
            countListenter.CountListenter(goods, num, true);
            upCarCount(goods.getShoppingcarId(), goods.getSize(), holder.tv_num);

        });

        holder.iv_subtract.setOnClickListener(view -> {
            int num = goods.getSize();
            if (num == 1) {
                return;
            }
            num--;
            goods.setSize(num);
            countListenter.CountListenter(goods, num, false);
            upCarCount(goods.getShoppingcarId(), goods.getSize(), holder.tv_num);

        });

    }

    private void upCarCount(String goodsId, int goodsNum, TextView tv_num) {
        Map<String, String> map = new HashMap<>();
        map.put("num", goodsNum + "");
        map.put("token", userInfo.getToken());
        map.put("shoppingCarId", goodsId);
        RetrofitClient.getInstance(mContext)
                .createBaseApi()
                .upCar(map, new BaseSubscriber<ResponseBody>(mContext) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int code = json.getInt("code");
                            DialogUtils.dismissDialog();
                            if (code == 0) {
                                tv_num.setText(goodsNum+"");
                            } else {
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void check(ShoppingcarDto goods, ImageView iv_check) {
        if (goods.isSelect) {
            goods.setSelect(false);
            iv_check.setImageResource(R.drawable.wallet_recharge_checkbox);
            num--;
        } else {
            iv_check.setImageResource(R.drawable.address_complete);
            goods.setSelect(true);
            num++;
        }
        if (num == list.size()) {
            checkItemClickListener.checkItemClickListener(goods, true);
        } else {
            checkItemClickListener.checkItemClickListener(goods, false);
        }
    }

    @Override
    public int getItemCount() {
        if (list == null) {
            return 0;
        } else {
            return list.size();
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.ll_item)
        LinearLayout ll_item;

        @BindView(R.id.ll_check)
        LinearLayout ll_check;

        @BindView(R.id.iv_subtract)
        ImageView iv_subtract;

        @BindView(R.id.iv_add)
        ImageView iv_add;

        @BindView(R.id.iv_check)
        ImageView iv_check;

        @BindView(R.id.iv_image)
        ImageView iv_image;

        @BindView(R.id.tv_title)
        TextView tv_title;

        @BindView(R.id.tv_money)
        TextView tv_money;

        @BindView(R.id.tv_num)
        TextView tv_num;

        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    public interface CheckItemClickListener {
        /**
         * 选择商品
         *
         * @param goods
         * @param isStoreSelect 是否全选
         */
        void checkItemClickListener(ShoppingcarDto goods, boolean isStoreSelect);
    }

    public interface LongItemListener {
        void LongItemLister(ShoppingcarDto goods, int position);
    }

    public interface CountListenter {
        void CountListenter(ShoppingcarDto goods, int num, boolean isOperation);
    }

    public interface ItemClickListener {
        void ItemClickListener(String shopId);
    }
}
